<?php

namespace service\util;
use think\image\Exception;
use think\Response;

class Image {

    const TYPE_CROP = 'crop';
    const TYPE_SCALE = 'scale';
    /**
     * 缩略图处理逻辑
     * @param $img_url
     * @param string $type
     * @param array $param
     * @return Response
     */
    public static function thumb($img_url, $type = self::TYPE_CROP, $param = []) {
        if (strpos($img_url,config('img_host')) !== false) {
            $path = str_replace(config('img_host'),'',$img_url);
            try {
                $image = \think\Image::open(PUBLIC_PATH.'static/'.$path);
            } catch (Exception $e) {
                return response('图片不存在',404);
            }
        } elseif (strpos($img_url,config('upload_host')) !== false) {
            $path = str_replace(config('upload_host'),'',$img_url);
            try {
                $image = \think\Image::open(PUBLIC_PATH.'uploads/'.$path);
            } catch (Exception $e) {
                return response('图片不存在',404);
            }
        } else {
            return response('非法请求',403);
        }
        if ($type === self::TYPE_SCALE) {
            $scale = isset($param['scale']) ? $param['scale'] : 50;
            $width = (int)($image->width() * $scale / 100);
            $height = (int)($image->height() * $scale / 100);
        } else {
            $width = isset($param['width']) ? $param['width'] : 150;
            $height = isset($param['height']) ? $param['height'] : 150;
            $width = (int)$width;
            $height = (int)$height;
        }
        $thumb_path = PUBLIC_PATH.'uploads/thumb';
        if (!is_dir($thumb_path)) {
            @mkdir($thumb_path,0777);
        }
        // 缩略图文件名：md5(原图地址)-宽*高.png(jpeg,jpg,gif......)
        $new_file_name = md5($img_url)."-".$width."x".$height.'.'.$image->type();
        $new_file_path = $thumb_path.'/'.$new_file_name;
        // 缩略图文件保存在/public/thumb/文件夹下，如果不存在，生成保存缩略图
        if (!file_exists($new_file_path)) {
            if ($type === self::TYPE_SCALE) {
                $image->thumb($width,$height,\think\Image::THUMB_SCALING);
            } else {
                $image->thumb($width,$height,\think\Image::THUMB_CENTER);
            }
        }
        // 输出图片
//         return response(file_get_contents($new_file_path),200)->contentType('image/'.$image->type());
        // 重定向到缩略图地址
        return redirect(config('upload_host').'thumb/'.$new_file_name);
    }

    ////blurFactor的值代表模糊程度，savepath为空时候直接覆盖，savename为空直接用原名
    public function gaussian_blur($srcImg="",$savepath=null,$savename=null,$blurFactor=5){
//        $srcImg=config('file_upload_path_base').'1.jpg';
//        $savename = '2.jpg';
        $gdImageResource=$this->image_create_from_ext($srcImg);
        $srcImgObj=$this->blur($gdImageResource,$blurFactor);
        $temp = pathinfo($srcImg);
        $name = $temp['basename'];
        $path = $temp['dirname'];
        $exte = $temp['extension'];
        $savename = $savename ? $savename : $name;
        $savepath = $savepath ? $savepath : $path;
        $savefile = $savepath .'/'. $savename;
        $srcinfo = @getimagesize($srcImg);
        switch ($srcinfo[2]) {
            case 1: imagegif($srcImgObj, $savefile); break;
            case 2: imagejpeg($srcImgObj, $savefile); break;
            case 3: imagepng($srcImgObj, $savefile); break;
            default: return '保存失败'; //保存失败
        }
        return $savefile;
//        imagedestroy($srcImgObj); //不用删除 原图片，原图片还有用。
    }
    /**
     * Strong Blur
     *
     * @param $gdImageResource 图片资源
     * @param $blurFactor   可选择的模糊程度
     * 可选择的模糊程度 0使用 3默认 超过5时 极其模糊
     * @return GD image 图片资源类型
     * @author Martijn Frazer, idea based on http://stackoverflow.com/a/20264482
     */
    private function blur($gdImageResource, $blurFactor = 5)
    {
        // blurFactor has to be an integer
        $blurFactor = round($blurFactor);
        $originalWidth = imagesx($gdImageResource);
        $originalHeight = imagesy($gdImageResource);
        $smallestWidth = ceil($originalWidth * pow(0.5, $blurFactor));
        $smallestHeight = ceil($originalHeight * pow(0.5, $blurFactor));
        // for the first run, the previous image is the original input
        $prevImage = $gdImageResource;
        $prevWidth = $originalWidth;
        $prevHeight = $originalHeight;
        // scale way down and gradually scale back up, blurring all the way
        for($i = 0; $i < $blurFactor; $i += 1)
        {
            // determine dimensions of next image
            $nextWidth = $smallestWidth * pow(2, $i);
            $nextHeight = $smallestHeight * pow(2, $i);
            // resize previous image to next size
            $nextImage = imagecreatetruecolor($nextWidth, $nextHeight);
            imagecopyresized($nextImage, $prevImage, 0, 0, 0, 0,
                $nextWidth, $nextHeight, $prevWidth, $prevHeight);
            // apply blur filter
            imagefilter($nextImage, IMG_FILTER_GAUSSIAN_BLUR);
            // now the new image becomes the previous image for the next step
            $prevImage = $nextImage;
            $prevWidth = $nextWidth;
            $prevHeight = $nextHeight;
        }
        // scale back to original size and blur one more time
        imagecopyresized($gdImageResource, $nextImage,
            0, 0, 0, 0, $originalWidth, $originalHeight, $nextWidth, $nextHeight);
        imagefilter($gdImageResource, IMG_FILTER_GAUSSIAN_BLUR);
        // clean up
        imagedestroy($prevImage);
        // return result
        return $gdImageResource;
    }
    private function image_create_from_ext($imgfile)
    {
        ini_set("memory_limit", "10000M");
        $info = getimagesize($imgfile);
        $im = null;
        switch ($info[2]) {
            case 1: $im=imagecreatefromgif($imgfile); break;
            case 2: $im=imagecreatefromjpeg($imgfile); break;
            case 3: $im=imagecreatefrompng($imgfile); break;
        }
        return $im;
    }

}